package BinaryTree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class LevelOrderTraversal {
    public List<List<Integer>> levelOrder(TreeNode root){
        ArrayList<List<Integer>> arrayList = new ArrayList<>();
        if(root == null){
            return arrayList;
        }

        ArrayDeque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        while(!deque.isEmpty()){
            ArrayList<Integer> list = new ArrayList<>();
            int len = deque.size();
            while(len-- > 0 ){
                TreeNode node = deque.poll();
                list.add(node.val);
                if(node.left != null){
                    deque.add(node.left);
                }
                if(node.right != null){
                    deque.add(node.right);
                }
            }
            arrayList.add(list);
        }
        return arrayList;
    }
}
